﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace VRacer
{
    public class Util
    {
        public static bool IsFinishCrossed(double CarVectorStartX, double CarVectorStartY, double CarVectorEndX, double CarVectorEndY,
            double FinishStartX, double FinishStartY, double FinishEndX, double FinishEndY)
        {

            Point FinishStart = new Point(FinishStartX, FinishStartY);
            Point FinishEnd = new Point(FinishEndX, FinishEndY);


            Point CarVectorStart = new Point(CarVectorStartX, CarVectorStartY);
            Point CarVectorEnd = new Point(CarVectorEndX, CarVectorEndY);
            double PointX, PointY; // point of intersection
            double k1, k2, b1, b2; //k1x + b1 k2x+b2

            Point Buffer;
            //let's find k1 and k2
            if (CarVectorStart.X > CarVectorEnd.X)
            {
                Buffer = CarVectorStart;
                CarVectorStart = CarVectorEnd;
                CarVectorEnd = Buffer;
            }

            if (FinishStart.X > FinishEnd.X)
            {
                Buffer = FinishStart;
                FinishStart = FinishEnd;
                FinishEnd = Buffer;
            }


            if (CarVectorStart.Y == CarVectorEnd.Y)
                k1 = 0;
            else
                k1 = (CarVectorEnd.Y - CarVectorStart.Y) / (CarVectorEnd.X - CarVectorStart.X);


            if (FinishStart.Y == FinishEnd.Y)
                k2 = 0;
            else
                k2 = (FinishEnd.Y - FinishStart.Y) / (FinishEnd.X - FinishStart.X);


            if (Math.Abs(k1 - k2) < double.Epsilon) // lines are parallel
                return false;

            b1 = CarVectorStart.Y - k1 * CarVectorStart.X;
            b2 = FinishStart.Y - k2 * FinishStart.X;

            PointX = (b2 - b1) / (k1 - k2);
            PointY = k1 * PointX + b1;

            if (IsNumberBetween(PointX, CarVectorStart.X, CarVectorEnd.X) &&
                IsNumberBetween(PointY, FinishStart.Y, FinishEnd.Y))
                return true;
            else
                return false;
        }

        public static bool IsNumberBetween(double checkNumber, double bound1, double bound2)
        {
            double MaxValue, MinValue;
            if (bound1 > bound2)
            {
                MaxValue = bound1;
                MinValue = bound2;
            }
            else
            {
                MaxValue = bound2;
                MinValue = bound1;
            }
            if (MinValue < checkNumber && checkNumber < MaxValue)
                return true;
            else
                return false;
        }
    }
}
